import { useCarStore } from '@/stores/car'
import { i18n } from '@/utils'
import { ElNotification, type FormInstance } from 'element-plus'
import { ref, toRaw, type Ref } from 'vue'

export const useConfig = () => {
  const formVisible = ref(false)
  const carStore = useCarStore()

  const formRef: Ref<FormInstance | undefined> = ref()

  const formData = ref<Record<string, any>>({})

  const loading = ref(false)

  const tableData = ref<unknown[]>([])

  function handleVisible() {
    if (!carStore.currentCar) {
      ElNotification({
        title: i18n.global.t('ti-shi'),
        message: i18n.global.t('qing-xuan-ze-che-liang')
      })
      return
    }
    openDialog()
  }

  function openDialog() {
    formVisible.value = true
  }

  function closeDialog() {
    formVisible.value = false
  }

  function setForm(val: any, key?: string) {
    if (key) {
      formData.value[key] = val
    } else {
      formData.value = val
    }
  }

  function openLoading() {
    loading.value = true
  }

  function closeLoading() {
    loading.value = false
  }

  function handleCancel() {
    setForm({})
    formRef.value?.resetFields()
    closeDialog()
  }

  function handleEdit<T>(data: T) {
    openDialog()
    setForm(Object.assign({}, toRaw(data)))
  }

  return {
    formVisible,
    handleVisible,
    openDialog,
    closeDialog,
    formData,
    setForm,
    loading,
    openLoading,
    closeLoading,
    tableData,
    handleCancel,
    handleEdit,
    formRef
  }
}
